#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WebDAV用户管理器
提供用户的增删改查功能
"""

import sys
import os
from typing import List, Optional, Dict, Any
from datetime import datetime

# 添加项目根目录到路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from src.common.database import get_session
from src.common.unified_logging import get_logger
from src.models.user import WebDAVUser, WebDAVUserRepository


class UserManager:
    """WebDAV用户管理器"""
    
    def __init__(self):
        self.logger = get_logger(__name__)
    
    def add_user(self, username: str, password: str, root_path: str = '/', 
                 can_read: bool = True, can_write: bool = True, can_delete: bool = True) -> bool:
        """添加用户
        
        Args:
            username: 用户名
            password: 密码
            root_path: 用户根路径
            can_read: 读权限
            can_write: 写权限
            can_delete: 删除权限
            
        Returns:
            bool: 是否成功
        """
        try:
            with get_session() as session:
                user_repo = WebDAVUserRepository()
                
                # 检查用户是否已存在
                existing_user = user_repo.find_by_username(username)
                if existing_user:
                    self.logger.error(f"用户 '{username}' 已存在")
                    return False
                
                # 创建用户
                user = user_repo.create_user(
                    username=username,
                    password=password,
                    root_path=root_path,
                    can_read=can_read,
                    can_write=can_write,
                    can_delete=can_delete
                )
                
                self.logger.info(f"用户 '{username}' 创建成功，ID: {user.id}")
                return True
                
        except Exception as e:
            self.logger.error(f"添加用户失败: {e}")
            return False
    
    def reset_password(self, username: str, new_password: str) -> bool:
        """重置用户密码
        
        Args:
            username: 用户名
            new_password: 新密码
            
        Returns:
            bool: 是否成功
        """
        try:
            with get_session() as session:
                user_repo = WebDAVUserRepository()
                
                # 查找用户
                user = user_repo.find_by_username(username)
                if not user:
                    self.logger.error(f"用户 '{username}' 不存在")
                    return False
                
                # 重置密码
                success = user_repo.change_password(user.id, new_password)
                if success:
                    self.logger.info(f"用户 '{username}' 密码重置成功")
                    return True
                else:
                    self.logger.error(f"用户 '{username}' 密码重置失败")
                    return False
                    
        except Exception as e:
            self.logger.error(f"重置密码失败: {e}")
            return False
    
    def disable_user(self, username: str) -> bool:
        """禁用用户
        
        Args:
            username: 用户名
            
        Returns:
            bool: 是否成功
        """
        try:
            with get_session() as session:
                user_repo = WebDAVUserRepository()
                
                # 查找用户
                user = user_repo.find_by_username(username)
                if not user:
                    self.logger.error(f"用户 '{username}' 不存在")
                    return False
                
                # 禁用用户
                success = user_repo.deactivate_user(user.id)
                if success:
                    self.logger.info(f"用户 '{username}' 已禁用")
                    return True
                else:
                    self.logger.error(f"用户 '{username}' 禁用失败")
                    return False
                    
        except Exception as e:
            self.logger.error(f"禁用用户失败: {e}")
            return False
    
    def enable_user(self, username: str) -> bool:
        """启用用户
        
        Args:
            username: 用户名
            
        Returns:
            bool: 是否成功
        """
        try:
            with get_session() as session:
                user_repo = WebDAVUserRepository()
                
                # 查找用户
                user = user_repo.find_by_username(username)
                if not user:
                    self.logger.error(f"用户 '{username}' 不存在")
                    return False
                
                # 启用用户
                success = user_repo.activate_user(user.id)
                if success:
                    self.logger.info(f"用户 '{username}' 已启用")
                    return True
                else:
                    self.logger.error(f"用户 '{username}' 启用失败")
                    return False
                    
        except Exception as e:
            self.logger.error(f"启用用户失败: {e}")
            return False
    
    def list_users(self, show_all: bool = False) -> List[Dict[str, Any]]:
        """列出用户
        
        Args:
            show_all: 是否显示所有用户（包括禁用的）
            
        Returns:
            List[Dict]: 用户列表
        """
        try:
            with get_session() as session:
                user_repo = WebDAVUserRepository()
                
                if show_all:
                    # 获取所有用户
                    from src.models.base import QueryCondition
                    condition = QueryCondition()
                    users = user_repo.list_by_condition(condition, order_by='username')
                else:
                    # 只获取活跃用户
                    users = user_repo.find_active_users()
                
                result = []
                for user in users:
                    result.append({
                        'id': user.id,
                        'username': user.username,
                        'is_active': user.is_active,
                        'root_path': user.root_path,
                        'can_read': user.can_read,
                        'can_write': user.can_write,
                        'can_delete': user.can_delete,
                        'created_at': user.created_at,
                        'updated_at': user.updated_at
                    })
                
                return result
                
        except Exception as e:
            self.logger.error(f"列出用户失败: {e}")
            return []
    
    def find_user(self, username: str) -> Optional[Dict[str, Any]]:
        """查找用户
        
        Args:
            username: 用户名
            
        Returns:
            Optional[Dict]: 用户信息，不存在返回None
        """
        try:
            with get_session() as session:
                user_repo = WebDAVUserRepository()
                
                user = user_repo.find_by_username(username)
                if not user:
                    return None
                
                return {
                    'id': user.id,
                    'username': user.username,
                    'is_active': user.is_active,
                    'root_path': user.root_path,
                    'can_read': user.can_read,
                    'can_write': user.can_write,
                    'can_delete': user.can_delete,
                    'created_at': user.created_at,
                    'updated_at': user.updated_at
                }
                
        except Exception as e:
            self.logger.error(f"查找用户失败: {e}")
            return None
    
    def update_permissions(self, username: str, can_read: bool = None, 
                          can_write: bool = None, can_delete: bool = None) -> bool:
        """更新用户权限
        
        Args:
            username: 用户名
            can_read: 读权限
            can_write: 写权限
            can_delete: 删除权限
            
        Returns:
            bool: 是否成功
        """
        try:
            with get_session() as session:
                user_repo = WebDAVUserRepository()
                
                # 查找用户
                user = user_repo.find_by_username(username)
                if not user:
                    self.logger.error(f"用户 '{username}' 不存在")
                    return False
                
                # 更新权限
                success = user_repo.update_permissions(
                    user.id, 
                    can_read=can_read,
                    can_write=can_write,
                    can_delete=can_delete
                )
                
                if success:
                    self.logger.info(f"用户 '{username}' 权限更新成功")
                    return True
                else:
                    self.logger.error(f"用户 '{username}' 权限更新失败")
                    return False
                    
        except Exception as e:
            self.logger.error(f"更新用户权限失败: {e}")
            return False
    
    def delete_user(self, username: str) -> bool:
        """删除用户
        
        Args:
            username: 用户名
            
        Returns:
            bool: 是否成功
        """
        try:
            with get_session() as session:
                user_repo = WebDAVUserRepository()
                
                # 查找用户
                user = user_repo.find_by_username(username)
                if not user:
                    self.logger.error(f"用户 '{username}' 不存在")
                    return False
                
                # 删除用户
                success = user_repo.delete_by_id(user.id)
                if success:
                    self.logger.info(f"用户 '{username}' 删除成功")
                    return True
                else:
                    self.logger.error(f"用户 '{username}' 删除失败")
                    return False
                    
        except Exception as e:
            self.logger.error(f"删除用户失败: {e}")
            return False
    
    def authenticate_user(self, username: str, password: str) -> Optional[Dict[str, Any]]:
        """用户认证
        
        Args:
            username: 用户名
            password: 密码
            
        Returns:
            Optional[Dict]: 认证成功返回用户信息，失败返回None
        """
        try:
            with get_session() as session:
                user_repo = WebDAVUserRepository()
                
                user = user_repo.authenticate(username, password)
                if not user:
                    return None
                
                return {
                    'id': user.id,
                    'username': user.username,
                    'is_active': user.is_active,
                    'root_path': user.root_path,
                    'can_read': user.can_read,
                    'can_write': user.can_write,
                    'can_delete': user.can_delete,
                    'created_at': user.created_at,
                    'updated_at': user.updated_at
                }
                
        except Exception as e:
            self.logger.error(f"用户认证失败: {e}")
            return None


# 全局实例
_user_manager = None


def get_user_manager() -> UserManager:
    """获取全局用户管理器实例"""
    global _user_manager
    if _user_manager is None:
        _user_manager = UserManager()
    return _user_manager


if __name__ == "__main__":
    # 测试用户管理器
    import logging
    logging.basicConfig(level=logging.INFO)
    
    manager = get_user_manager()
    
    # 测试添加用户
    print("测试添加用户...")
    success = manager.add_user("testuser", "testpass123", "/test")
    print(f"添加用户结果: {success}")
    
    # 测试查找用户
    print("\n测试查找用户...")
    user_info = manager.find_user("testuser")
    print(f"用户信息: {user_info}")
    
    # 测试列出用户
    print("\n测试列出用户...")
    users = manager.list_users(show_all=True)
    for user in users:
        print(f"用户: {user['username']}, 状态: {'活跃' if user['is_active'] else '禁用'}")
